package com.vineetmanohar.nitrogen;

import java.io.File;
import java.io.IOException;

public class NitrogenUtils {
	/**
	 * What would be the new path of file with the given absolute path when
	 * copied from basedir1 to basedir2 such that the relative path to the
	 * basedir remains the same
	 * 
	 * @param absolutePath
	 * @param basedir1
	 * @param basedir2
	 * @return
	 */
	public static File getProjectedPath(File absolutePath, File basedir1,
			File basedir2) {
		String relativePath = getRelativePath(absolutePath, basedir1);

		return new File(basedir2, relativePath);
	}

	public static String getRelativePath(File file, File basedir1) {
		try {
			String basePath = basedir1.getCanonicalPath();
			String fullPath = file.getCanonicalPath();
			if (fullPath.indexOf(basePath) != 0) {
				throw new NitrogenException(
						"File not contained in basedir. File=" + fullPath
								+ ", base=" + basePath, null);
			}

			return fullPath.substring(basePath.length(), fullPath.length());
		} catch (IOException e) {
			throw new NitrogenException(
					"Error occurred while calculating relative path for "
							+ file + ", base=" + basedir1, e);
		}
	}
}